﻿#include "GraphInterpolator.h"
#include "lang/Exception.h"
#include "lang/StringFormat.hpp"
using namespace yzrilyzr_util;
using namespace yzrilyzr_array;
using namespace yzrilyzr_lang;

namespace yzrilyzr_interpolator{
	GraphInterpolator::~GraphInterpolator(){}
	GraphInterpolator::GraphInterpolator(DoubleArray xys) : xys(xys){}
	GraphInterpolator::GraphInterpolator(std::initializer_list<double> xys){
		this->xys=DoubleArray(xys);
	}

	u_normal_01 GraphInterpolator::y(u_normal_01 x){
		if(xys == nullptr)return 0;
		uint32_t index=0;
		if(x <= xys[0]) return xys[1];
		if(x >= xys[xys.length - 2]) return xys[xys.length - 1];
		for(;index + 3 < xys.length;index+=2){
			double gx1=xys[index];
			double gy1=xys[index + 1];
			double gx2=xys[index + 2];
			double gy2=xys[index + 3];
			if(gx1 < x && x <= gx2){
				double xInRange=(x - gx1) / (gx2 - gx1);
				double deltaY=gy2 - gy1;
				return gy1 + deltaY * xInRange;
			}
		}
		throw IllegalStateException("x not in range");
	}
	String GraphInterpolator::toString() const{
		return StringFormat::object2string("GraphInterpolator", xys);
	}
}